﻿using Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Web.PublicWeb
{
    public class LoginCookie
    {
        private static readonly string Babyface = "Babyface";
        private static readonly string UserInfo = "UserInfo";

        public static void LoginUser(SysUser user)
        {
            if(user == null)
            {
                ClearCookie();
                return;
            }
            HttpCookie cookieBabyface = new HttpCookie(Babyface);
            string jsonUser = JsonConvert.SerializeObject(user);
            jsonUser = HttpContext.Current.Server.UrlEncode(jsonUser);
            cookieBabyface.Values.Add(UserInfo, jsonUser);
            cookieBabyface.Expires = DateTime.Now + new TimeSpan(0, 12, 0, 0);//cookie过期时间12小时
            HttpContext.Current.Response.AppendCookie(cookieBabyface);
        }

        public static SysUser GetUser()
        {
            HttpCookie cookieBabyface = HttpContext.Current.Request.Cookies[Babyface];
            if (cookieBabyface != null)
            {
                string jsonUser = cookieBabyface[UserInfo];
                jsonUser = HttpContext.Current.Server.UrlDecode(jsonUser);
                try
                {
                    var user = JsonConvert.DeserializeObject<SysUser>(jsonUser);
                    return user;
                }
                catch
                {
                    return null;
                }
            }
            return null;
        }

        public static void ClearCookie()
        {
            if (HttpContext.Current.Request.Cookies[Babyface] != null)
            {
                HttpCookie cookieBabyface = HttpContext.Current.Request.Cookies[Babyface];
                cookieBabyface.Expires = DateTime.Now.AddDays(-1);
                HttpContext.Current.Response.Cookies.Add(cookieBabyface);
            }
        }
    }
}